import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import i18n from '@/i18n'
import { enable, disable, isEnabled } from '@tauri-apps/plugin-autostart'

// 主题类型
export type Theme = 'light' | 'dark' | 'auto'

// 语言类型
export type Language = 'zh-CN' | 'en-US'

// 设置接口
export interface AppSettings {
  theme: Theme
  language: Language
  autoStart: boolean
  showNotifications: boolean
  autoUpdate: boolean
  minimizeToTray: boolean
  startMinimized: boolean
  enableSounds: boolean
  maxHistorySize: number
  refreshInterval: number
}

// 默认设置
const defaultSettings: AppSettings = {
  theme: 'auto',
  language: 'zh-CN',
  autoStart: false,
  showNotifications: true,
  autoUpdate: true,
  minimizeToTray: true,
  startMinimized: false,
  enableSounds: true,
  maxHistorySize: 100,
  refreshInterval: 1000
}

export const useSettingsStore = defineStore('settings', () => {
  // 设置状态
  const settings = ref<AppSettings>({ ...defaultSettings })
  
  // 系统主题监听器
  let mediaQuery: MediaQueryList | null = null
  
  // 计算属性
  const isDarkMode = computed(() => {
    if (settings.value.theme === 'dark') return true
    if (settings.value.theme === 'light') return false
    // auto模式下根据系统主题
    if (typeof window !== 'undefined' && window.matchMedia) {
      return window.matchMedia('(prefers-color-scheme: dark)').matches
    }
    return false // 默认为浅色主题
  })
  
  const currentLanguage = computed(() => settings.value.language)
  
  // 应用主题到DOM
  const applyTheme = () => {
    if (typeof document === 'undefined') return
    
    const isDark = isDarkMode.value
    const htmlElement = document.documentElement
    
    if (isDark) {
      htmlElement.classList.add('dark')
    } else {
      htmlElement.classList.remove('dark')
    }
  }
  
  // 方法
  const updateSettings = async (newSettings: Partial<AppSettings>) => {
    const oldAutoStart = settings.value.autoStart
    settings.value = { ...settings.value, ...newSettings }
    
    if (newSettings.autoStart !== undefined && newSettings.autoStart !== oldAutoStart) {
      try {
        if (newSettings.autoStart) {
          await enable()
        } else {
          await disable()
        }
      } catch (error) {
        console.error('Failed to update autostart setting:', error)
        // Revert the setting if the native call fails
        settings.value.autoStart = oldAutoStart
      }
    }
    
    saveSettings()
    // 移除重复的主题应用，由watch监听器统一处理
  }
  
  const resetSettings = () => {
    settings.value = { ...defaultSettings }
    saveSettings()
    applyTheme()
  }
  
  const saveSettings = () => {
    try {
      localStorage.setItem('app_settings', JSON.stringify(settings.value))
    } catch (error) {
      console.error('保存设置失败:', error)
    }
  }
  
  const loadSettings = () => {
    try {
      const savedSettings = localStorage.getItem('app_settings')
      if (savedSettings) {
        const parsed = JSON.parse(savedSettings)
        settings.value = { ...defaultSettings, ...parsed }
      }
    } catch (error) {
      console.error('加载设置失败:', error)
      settings.value = { ...defaultSettings }
    }
  }
  
  // 主题切换
  const toggleTheme = () => {
    const themes: Theme[] = ['light', 'dark', 'auto']
    const currentIndex = themes.indexOf(settings.value.theme)
    const nextIndex = (currentIndex + 1) % themes.length
    updateSettings({ theme: themes[nextIndex] })
  }
  
  const setTheme = (theme: Theme) => {
    updateSettings({ theme })
  }
  
  // 语言切换
  const setLanguage = (language: Language) => {
    updateSettings({ language })
    // 更新i18n语言
    i18n.global.locale.value = language
  }

  // 从外部同步自启状态，不触发后端调用
  const syncAutostartState = (isEnabled: boolean) => {
    if (settings.value.autoStart !== isEnabled) {
      settings.value.autoStart = isEnabled
      saveSettings() // 仅保存状态，不触发副作用
    }
  }
  
  // 设置系统主题监听器
  const setupSystemThemeListener = () => {
    if (typeof window === 'undefined' || !window.matchMedia) return
    
    if (mediaQuery) {
      mediaQuery.removeEventListener('change', handleSystemThemeChange)
    }
    
    mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', handleSystemThemeChange)
  }
  
  const handleSystemThemeChange = () => {
    if (settings.value.theme === 'auto') {
      applyTheme()
    }
  }
  
  // 监听主题变化
  watch(
    () => settings.value.theme,
    () => {
      applyTheme()
    },
    { immediate: true }
  )
  
  // 初始化
  const initialize = async () => {
    loadSettings()
    setupSystemThemeListener()
    // applyTheme() 由watch监听器处理，不需要重复调用
    // 设置初始语言
    try {
      i18n.global.locale.value = settings.value.language
      
      const isDev = import.meta.env.DEV

      if (isDev) {
        // 在开发模式下，强制禁用自启
        if (settings.value.autoStart) {
          settings.value.autoStart = false
          saveSettings()
        }
        // 同时确保系统级别的自启也被禁用
        try {
          if (await isEnabled()) {
            await disable()
          }
        } catch (e) {
          console.error('Failed to disable autostart in dev mode:', e)
        }
      } else {
        // 在生产模式下，同步状态
        const autostartEnabled = await isEnabled()
        if (settings.value.autoStart !== autostartEnabled) {
          settings.value.autoStart = autostartEnabled
          saveSettings()
        }
      }
    } catch (error) {
      console.error('设置语言或同步自启状态失败:', error)
    }
  }
  
  return {
    // 状态
    settings,
    
    // 计算属性
    isDarkMode,
    currentLanguage,
    
    // 方法
    updateSettings,
    resetSettings,
    saveSettings,
    loadSettings,
    toggleTheme,
    setTheme,
    setLanguage,
    syncAutostartState,
    applyTheme,
    initialize
  }
}) 